﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Security;
using PServiceBus.Gateway.Interfaces;
using PServiceBus.Core.Runtime;
using PServiceBus.Gateway.ZeroMQ;
using PServiceBus.Core.Interface;
using PServiceBus.Services.Gateway.Extensions;
using PServiceBus.Gateway.Interfaces.Exceptions;
using PServiceBus.Gateway.Redis;

namespace PServiceBus.Services.Gateway.Runtime {
    public class GatewayMessageBus {

        public static IMessageBus Create(string address, ESBIdentity identity, bool rethrowException, Dictionary<string, string> headers) {
            var bus = Get().Init(address);
            bus.Identity = identity;
            bus.ReThrowException = rethrowException;
            bus.Headers = headers;
            return bus;
        }

        private static IGatewayMessageBus Get() {
            var gateway = ServiceLocator<IGatewayMessageBus>.Get();

            if (gateway == null)
                ServiceLocator<IGatewayMessageBus>.Set(gateway = new RedisMessageBus());
            
            return gateway;
        }

        public static bool IsValidException(Exception ex) {
            var bus = Get() as GatewayMessageBusBase;
            try {
                if (bus != null) return bus.IsValidException(ex);
            } catch (Exception) {
                //Catch exception for scenario where exception needs to be serialized back to client
                if (ESB._reThrowException) 
                    throw;
            }
            return false;
        }
    }
}
